//
//  PictureSelectorViewController.swift
//  SinaWeibo
//
//  Created by apple on 15/11/19.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

private let column :CGFloat = 4

private let pictureCellMargin : CGFloat = 10

private let maxImageCount = 9

class PictureSelectorViewController: UICollectionViewController {

    
    //增加图片数组属性
    private var imageList = [UIImage]()
    
    /**
    
    
    初始化构造方法
    */
    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        let w  = (screenWidth - (column + 1) * pictureCellMargin) / column
        
        layout.itemSize = CGSizeMake(w, w)
        
        //设置参数
        
        layout.minimumLineSpacing = pictureCellMargin
        
        layout.minimumInteritemSpacing = pictureCellMargin
        
        //设置内边距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        super.init(collectionViewLayout: layout)
    }
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(selecteCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.imageList.count + ((imageList.count == maxImageCount) ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let  cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! selecteCell
        
        //item 的个数永远要比 图片 多一个
        if indexPath.row == imageList.count {
            
            cell.image = nil
            
        } else {
            
            cell.image = imageList[indexPath.row]
        }
        //设置代理
        cell.selectPcituredelegate = self
        
        return cell
    }
}
/**
*  实现协议方法
*/
extension PictureSelectorViewController:selecteCellDelegate {
    
    func willAddPicture(cell: selecteCell) {
        
        if cell.image != nil {
            print("已经添加图片")
            return
        }
        

        let picker = UIImagePickerController()
        
        //指定代理
        picker.delegate = self
        
        //设置头像的时候 打开允许编辑属性
        // picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func willDelegatePicture(cell: selecteCell) {
        
        let indexpath = collectionView?.indexPathForCell(cell)
        
        self.imageList.removeAtIndex((indexpath?.item)!)
        
        //刷新数据
        self.collectionView?.reloadData()
        
    }
}
extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //实现协议方法
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        imageList.append(image)
        
        //刷新数据
        collectionView?.reloadData()
        
        
        //消失的操作交给程序员
        dismissViewControllerAnimated(true, completion: nil)
    }
}
/**
*  定义代理方法
*/
protocol selecteCellDelegate:NSObjectProtocol {
    
    //定义协议方法  
    func willAddPicture(cell:selecteCell)
    
    func willDelegatePicture(cell:selecteCell)
    
}
class selecteCell: UICollectionViewCell {
    
    //定义代理
    weak var selectPcituredelegate:selecteCellDelegate?
    
    //监听按钮的单机方法
    @objc private func addBtnClick() {
        
       selectPcituredelegate?.willAddPicture(self)
    }
    
    @objc private func deleeBtnClick() {
        
        selectPcituredelegate?.willDelegatePicture(self)
    }
    //定义图片数据模型
    var image :UIImage?{
        
        didSet {
            
            deleteBtn.hidden = (image == nil)
            if image != nil {
                
                addBtn.setBackgroundImage(image, forState: .Normal)
                
            } else {
                
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    //MAARK 初始化方法
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUPUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     //MAARK 设置UI
    
    private func setUPUI () {
        
        //添加子控件
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        
        addBtn.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.right.equalTo(contentView)
        }
        
        //添加两个按钮的点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        deleteBtn.addTarget(self, action: "deleeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
     //MAARK 懒加载控件
    
    private lazy var addBtn: UIButton = UIButton(title: nil
        , backImage: "compose_pic_add", color: nil)
    
    private lazy var deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)

    
}